package ar.com.photo_admin.service

import groovy.json.JsonSlurper

import ar.com.photo_admin.domain.*;

class PurchaseOrderService extends BaseService {

    def exportService
	def notificationsService
	
    def parseFromJSON(jsonInput) {		
		def slurper = new JsonSlurper()
		def result = slurper.parseText(jsonInput)
		
		PurchaseOrder order = new PurchaseOrder();
		
		result.each {
			orderItem ->		
							
			order.addToOrderItems(new PurchaseOrderItem(
					size : Size.get(orderItem.size),
					paperBorder:  PaperBorder.get(orderItem.paperBorder),
					paperType:  PaperType.get(orderItem.paperType),
					photo: EventPhoto.get(orderItem.photoId),
					amountCopies: orderItem.amountPhotos							
				));
									
		}		
		
		if (order.orderItems != null){
			//Todas las fotos pertenecen al mismo fotografo
			order.photographer = order.orderItems.first().photo.event.photographer;
		}			
		
		order.calculateAmountOfItems();
		order.calculatePrice();		
		return order;
		
    }
	
	def saveJSONOrder(jsonOrder){
		PurchaseOrder order = parseFromJSON(jsonOrder)
		order.client = getLoggedUser();	
		order.save(flush:true)
	}
	
	
	def completeConfirmation(PurchaseOrder purchaseOrder){
		purchaseOrder.confirm()
		exportOrderToFile(purchaseOrder);		
		notificationsService.notifyNewOrder(purchaseOrder)
		purchaseOrder.save(flush:true)
	}
	
	def exportOrderToFile(purchaseOrder){
		log.info "Exportando a archivo";
		def exportedFile = new java.io.FileOutputStream(getOrdersRootPath()+"${purchaseOrder.id}.pdf");
		exportOrder(purchaseOrder,"pdf",exportedFile)
		
		log.info "Finalizada la exportacion a archivo";
		exportedFile.close();
	}
	
	def exportOrder(purchaseOrder,format,outputStream){
		
		log.info "Comenzando la exportacion";
		def purchaseOrderItemsList = purchaseOrder.orderItems
							
		List fields = ["photo","size", "paperType","paperBorder","amountCopies"]
		Map labels = ["photo": "Foto", "size": "Tamaño","paperType": "Papel", "paperBorder":"Borde","amountCopies":"Copias"]
							
		Map formatters = [:]
		Map parameters = [title: "Pedido N°${purchaseOrder.id}", "column.widths": [0.2, 0.2, 0.2, 0.2,0.2]]
				
		exportService.export(format, outputStream ,purchaseOrderItemsList, fields, labels, formatters, parameters)				
	}
	
	def listAllOrdersRecieved(params)
	{
		list(true, params)
	}
	
	def listAllOrdersMade(params)
	{		
		list(false, params)
	}
	
	def list(recieved,params)
	{
		def orders = recieved ? PurchaseOrder.findAllByPhotographer(getLoggedUser()) : PurchaseOrder.findAllByClient(getLoggedUser());
		def confirmedOrdersIds = orders.findAll ({PurchaseOrder o -> o.isRegistered()}).collect { o -> o.id }
		return (confirmedOrdersIds.size() > 0) ?
			PurchaseOrder.findAll("from PurchaseOrder where id in (:ids) order by id desc",[ids: confirmedOrdersIds],params) :
			[]
	}
	
	def finishOrder(orderId)
	{
		PurchaseOrder order = PurchaseOrder.get(orderId)
		order.finish();
		notificationsService.notifyOrderStatusChange(order);
	}
	
	
	def hasOrdered(user){
		return (PurchaseOrder.findByClient(user) != null)
	}
}
